package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.*;
import com.goods.business.service.OutStockService;
import com.goods.common.model.business.*;
import com.goods.common.response.ActiveUser;
import com.goods.common.vo.business.OutStockVO;
import com.goods.common.vo.system.PageVO;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class OutStockServiceImpl implements OutStockService {

    @Autowired
    private OutStockMapper outStockMapper;


    @Autowired
    private OutStockInfoMapper outStockInfoMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ConsumerMapper consumerMapper;




    /**
     * 出库单列表
     */
    @Override
    public PageVO<OutStockVO> findOutStockList(int pageNum, int pageSize, Integer status) {
        //根据条件查询
        Example example = new Example(OutStock.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",status);
        List<OutStock> outStocks = outStockMapper.selectByExample(example);
        if (outStocks!= null){
            List<OutStockVO> list = outStocks.stream().map(outStock -> {
                OutStockVO outStockVO = new OutStockVO();
                BeanUtils.copyProperties(outStock, outStockVO);

                //查询consumer
                Consumer consumer = consumerMapper.selectByPrimaryKey(outStockVO.getConsumerId());
                if (consumer != null){
                    outStockVO.setPhone(consumer.getPhone());
                    outStockVO.setAddress(consumer.getAddress());
                    outStockVO.setName(consumer.getName());
                }
                return outStockVO;
            }).collect(Collectors.toList());
            //构建分页条件
            PageHelper.startPage(pageNum,pageSize);
            PageInfo<OutStockVO> pageInfo = new PageInfo<>(list);
            //返回
            return new PageVO<OutStockVO>(pageInfo.getTotal(),pageInfo.getList());
        }
        return null;
    }

    /**
     * 添加出库单
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOutStock(OutStockVO outStockVO) {
        OutStock outStock = new OutStock();
        //先添加出库单
        BeanUtils.copyProperties(outStockVO,outStock);
        //set数据
        outStock.setCreateTime(new Date());
        //出库单号
        outStock.setOutNum(UUID.randomUUID().toString());

        if (outStockVO.getConsumerId() == null){
            Consumer consumer = new Consumer();
            BeanUtils.copyProperties(outStockVO,consumer);
            consumer.setCreateTime(new Date());
            consumer.setModifiedTime(new Date());
            consumerMapper.insert(consumer);
            outStock.setConsumerId(consumer.getId());
        }


        int nub = 0;

        List<Object> products = outStockVO.getProducts();
        for (Object Obj : products) {
            Map<String,Object> map = (Map<String, Object>) Obj;
            //获取数据
            Integer productId = Integer.valueOf(map.get("productId").toString());
            Integer productNumber = Integer.valueOf(map.get("productNumber").toString());
            //累加
            nub +=productNumber;
            //查询物资
            Product product = productMapper.selectByPrimaryKey(productId);

            //中间表赋值
            //添加中间表
            OutStockInfo outStockInfo = new OutStockInfo();
            outStockInfo.setCreateTime(new Date());
            outStockInfo.setModifiedTime(new Date());
            outStockInfo.setPNum(product.getPNum());
            outStockInfo.setOutNum(outStock.getOutNum());
            outStockInfo.setProductNumber(productNumber);
            //添加到中间表
            outStockInfoMapper.insert(outStockInfo);
        }

        //赋值用户名
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        outStock.setOperator(activeUser.getUser().getUsername());

        //赋值
        outStock.setProductNumber(nub);
        outStock.setStatus(2);
        //添加
        outStockMapper.insert(outStock);

    }


    /**
     * 审核
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publish(Long id) {
        //更新状态
        OutStock outStock = outStockMapper.selectByPrimaryKey(id);
        outStock.setStatus(0);
        outStockMapper.updateByPrimaryKey(outStock);

        //查询中间表
        Example example1 = new Example(OutStockInfo.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("outNum",outStock.getOutNum());
        List<OutStockInfo> outStockInfos = outStockInfoMapper.selectByExample(example1);

        //判断
        if (outStockInfos != null){
            for (OutStockInfo outStockInfo : outStockInfos) {

                //减库存
                Example example = new Example(ProductStock.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("pNum",outStockInfo.getPNum());
                ProductStock productStock = productStockMapper.selectOneByExample(example);
                //判断库存
                if (productStock.getStock() > outStockInfo.getProductNumber()){
                    productStock.setStock(productStock.getStock() - outStockInfo.getProductNumber());
                    productStockMapper.updateByPrimaryKey(productStock);
                }else {
                    throw new RuntimeException("库存不足");
                }
            }
        }
    }
}
